import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import * as R from 'ramda';

import { getMarkdown } from '../markdown/index';
import { request } from './request';

declare var $: any;

@Component({
  selector: 'app-dir',
  templateUrl: './dir.component.html',
  styleUrls: ['./dir.component.scss']
})
export class DirComponent implements OnInit {

  public path: string[];
  public result: any[];

  async ngOnInit() {
    const raw: any[] = await request(`http://127.0.0.1:3000/files`);
    const files = raw.map(({ fileID, filePath, fileName }) => ({
      id: fileID,
      path: filePath.split('/'),
      name: fileName,
    }));

    const filted = R.filter((file) => {
      const path = this.path;
      const filepath: string[] = file.path;
      return R.equals(filepath.slice(0, path.length), path);
    }, files);

    const result = R.map((file) => {
      const path = this.path;
      const filepath: string[] = file.path;
      if (R.equals(path, filepath)) {
        return {
          type: 'file',
          path: file.path,
          name: file.name,
          id: file.id,
        };
      } else {
        return {
          type: 'dir',
          name: filepath[path.length],
          id: filepath.slice(0, path.length + 1).join('/'),
        };
      }
    }, filted);

    const sorted = R.sortBy(R.prop('type'), result);
    if (!R.equals(this.path, [])) {
      sorted.unshift({
        type: 'back',
        name: '返回上一页',
        id: this.path.slice(0, -1).join('/'),
      });
    }
    this.result = R.uniq(sorted);
  }

  constructor(
    private route: ActivatedRoute,
  ) {
      this.route.url
        .map(R.map(R.prop('path')))
        .subscribe((path: string[]) => this.path = path);
  }

  async remove(file) {
    const fileID = file.id;
    const req = await request(`http://127.0.0.1:3000/file/${fileID}`, {
      method: 'DELETE',
    });
    location.reload();
  }

  async rmdir(card) {
    const path = card.id;
    const req = await request(`http://127.0.0.1:3000/files?filePath=${path}`, {
      method: 'DELETE',
    });
    location.reload();
  }

  rename(file) {
    const id = file.id;
    const name = file.name;
    const path = file.path;
    $('#rename-title').text(name);
    $('#rename-id').val(id);
    $('#rename-input').val(name);
    $('#rename').modal('show');
  }

  async afterRename() {
    const id = $('#rename-id').val();
    const path = $('#rename-input').val();
    const req = await request(`http://127.0.0.1:3000/file/${id}`);
    const file = req[0];
    file.fileName = path;
    await request(`http://127.0.0.1:3000/file/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(file),
    });
    location.reload();
  }

  move(file) {
    const id = file.id;
    const name = file.name;
    const path = file.path;
    $('#move-title').text(name);
    $('#move-id').val(id);
    $('#move-input').val(path.join('/'));
    $('#move').modal('show');
  }

  async afterMove() {
    const id = $('#move-id').val();
    const path = $('#move-input').val();
    const req = await request(`http://127.0.0.1:3000/file/${id}`);
    const file = req[0];
    file.filePath = path;
    await request(`http://127.0.0.1:3000/file/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(file),
    });
    location.reload();
  }

  add(file) {
    $('#add-title').text('add file');
    $('#add-name').val('');
    $('#add-path').val(this.path.join('/'));
    $('#add').modal('show');
  }

  async afterAdd() {
    const name = $('#add-name').val();
    const path = $('#add-path').val();
    const file = {
      filePath: path,
      fileName: name,
      fileCnt: '',
    }
    await request(`http://127.0.0.1:3000/file`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(file),
    });
    location.reload();
  }

}
